<template>
  <div class="container">
    <div class="search">
      <el-select v-model="params.status" placeholder="轮播图状态" clearable>
        <el-option label="正常" value="0"></el-option>
        <el-option label="封禁" value="1"></el-option>
      </el-select>
      <el-button type="primary" @click="findBySearch">搜索</el-button>
      <el-button type="warning" @click="clearParams">清空</el-button>
      <el-button type="success" @click="addBanner">新增</el-button>
    </div>

    <div class="table">
      <el-table :data="bannerData" stripe highlight-current-row style="width: 100%" height="75vh">
        <el-table-column label="序号" prop="id" sortable align="center"></el-table-column>

        <el-table-column label="轮播图" prop="pic" align="center">
          <template #default="{ row }">
            <el-image
              style="width: 70px; height: 70px; border-radius: 50%"
              :src="'http://localhost:8080/api/files/' + row.pic"
              :preview-src-list="['http://localhost:8080/api/files/' + row.pic]"
            ></el-image>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="账号状态" prop="status" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.sts" @change="updateStatus(row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center">
          <template #default="{ row }">
            <el-button type="primary" @click="editBanner(row)">编辑</el-button>
            <el-button type="success" @click="downLoad(row)">下载</el-button>

            <el-popconfirm
              title="你确定删除吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="deleteBanner(row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="params.pageNum"
        v-model:page-size="params.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        size="default"
        layout="total, sizes, prev, pager, next, jumper"
        :total="params.total"
        @size-change="findBySearch"
        @current-change="findBySearch"
      />
    </div>

    <div class="dialog">
      <!-- 新增or修改 -->
      <el-dialog v-model="dialogVisible" width="30%" align-center>
        <template #header>
          <div style="margin: 20px auto; width: fit-content; font-size: 20px">添加轮播图信息</div>
        </template>
        <el-form :model="params">
          <el-form-item label="轮播图" label-width="22%">
            <el-upload
              action="http://localhost:8080/api/files/upload?fileDir=swiper"
              list-type="picture-card"
              :auto-upload="true"
              :limit="1"
              :on-success="successUpload"
              :on-remove="handleRemove"
              :on-preview="handlePicturePreview"
              :file-list="picList"
              :class="{ 'none-up': uploadDisabled }"
            >
              <i-ep-plus />
            </el-upload>
          </el-form-item>
          <el-form-item label="轮播图状态" label-width="22%">
            <el-radio-group v-model="params.status">
              <el-radio value="0">正常</el-radio>
              <el-radio value="1">封禁</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </template>
      </el-dialog>
      <!-- 轮播图片预览 -->
      <el-dialog v-model="preImgVisible" width="600" align-center>
        <img :src="'http://localhost:8080/api/files/' + params.pic" alt="头像预览" style="width: 100%" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { bannerDeleteApi, bannerFindBySearchApi, bannerSaveApi } from '@/api/banner'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'

const params = ref({
  status: '',
  pic: '',
  id: '',
  pageNum: 1,
  pageSize: 5,
  total: '',
})

const picList: any = ref([])

const uploadDisabled = ref(false)

const dialogVisible = ref(false)

const preImgVisible = ref(false)

const bannerData: any = ref([])

onMounted(() => {
  findBySearch()
})

const findBySearch = async () => {
  // TODO:想要达到当搜索清空的时候都从1开始
  // params.value.pageNum = 1
  let res = await bannerFindBySearchApi(params.value)
  bannerData.value = res.data.list.map((item: any) => ({
    ...item,
    sts: item.status === '0',
  }))
  params.value.total = res.data.total
}

const clearParams = () => {
  params.value.status = ''
  findBySearch()
}

const addBanner = () => {
  uploadDisabled.value = false
  dialogVisible.value = true
}

const editBanner = (row: any) => {
  console.log('该行数据row:', row)
  uploadDisabled.value = true
  dialogVisible.value = true
  // TODO:共享引用问题
  // params.value = row
  Object.assign(params.value, row)
  picList.value = [{ name: params.value.pic, url: 'http://localhost:8080/api/files/' + params.value.pic }]
}

const submit = async () => {
  if (params.value.pic) {
    await bannerSaveApi(params.value)
    ElMessage.success(params.value.id ? '修改成功' : '添加成功')
    dialogVisible.value = false
  } else {
    ElMessage.warning('请先选择图片')
  }
}

const updateStatus = async (row: any) => {
  row.status = row.status === '0' ? '1' : '0'
  await bannerSaveApi(row)
  ElMessage.success('修改轮播图状态成功')
  findBySearch()
}

const downLoad = (row: any) => {
  location.href = 'http://localhost:8080/api/files/' + row.pic
}

const deleteBanner = async (row: any) => {
  await bannerDeleteApi(row.id)
  ElMessage.success('删除成功')
  findBySearch()
}

// 头像上传成功
const successUpload = (res: any, file: any, fileList: any) => {
  picList.value = fileList
  uploadDisabled.value = picList.value.length >= 1
  params.value.pic = res.data
}
// 删除头像
const handleRemove = (file: any, fileList: any) => {
  let index = picList.value.findIndex((item: any) => {
    return item.uid === file.uid
  })
  picList.value.splice(index, 1)
  uploadDisabled.value = picList.value.length >= 1
  params.value.pic = ''
}
// 预览头像
const handlePicturePreview = (file: any) => {
  preImgVisible.value = true
}

watch(dialogVisible, (newValue, oldValue) => {
  if (newValue === false) {
    params.value.id = ''
    params.value.pic = ''
    params.value.status = ''
    picList.value = []
  }
})
</script>

<style scoped lang="scss">
.container {
  .search {
    display: flex;
    flex-wrap: nowrap;

    .el-select {
      width: 130px;
      margin-right: 10px;
    }
  }

  .table {
    margin: 15px 0;

    .el-switch {
      --el-switch-on-color: #13ce66;
      --el-switch-off-color: #ff4949;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
  }

  .dialog {
    .el-input,
    .el-select {
      width: 80%;
    }
  }
}

/* CSS */
.cell {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

// 深度选择器
.none-up ::v-deep(.el-upload--picture-card) {
  display: none;
}
</style>
